package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.remote.AuthRemote;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Admin;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author：贾维斯
 * @Description: 描述
 * @name：AuthServiceImpl
 * @Date：2024/11/4 9:34
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthRemote authRemote;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result<JwtResponse> selectAdmin(Admin admin) {
        String phone = admin.getPhone();
        String password = admin.getPassword();
        if (StringUtils.isAllBlank(phone,password)) {
            return Result.error("不能为空");
        }
        Result<Admin> admin1 = authRemote.findAdmin(admin);
        Admin data = admin1.getData();
        if (data==null) {
            return Result.error("用户名或密码错误");
        }
        String userKey = UUID.randomUUID().toString();
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(data),15, TimeUnit.MINUTES);

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setTime("15MIN");
        jwtResponse.setToken(token);
        return Result.success(jwtResponse);
    }

    @Override
    public Admin getInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(s,Admin.class);
    }
}
